package com.uflower.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

//public class FeignConifg {}
@Configuration
@Slf4j
public class FeignConifg {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
                HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
                if(request != null){
                    Cookie[] cookies = request.getCookies();
                    if(cookies != null &&cookies.length>0){
                        for (Cookie cookie : cookies) {
                            requestTemplate.header(cookie.getName(),cookie.getValue());
                            System.out.println("cookieName:"+cookie.getName()+"  value:"+cookie.getValue());
                        }
                    } else{
                        log.warn("FeignHeaderConfig设置失败");
                    }
                    String token = request.getHeader("token");
                    requestTemplate.header("token",token);
                }
                System.out.println("远程之前先进行RequestInterceptor");
            }
        };

    }
}
